package net.caixiaomi.info.ui.details;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.mobstat.StatService;
import com.google.gson.reflect.TypeToken;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.CommonFragmentPageAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.CommonTab;
import net.caixiaomi.info.model.CountMoneyCurrentMonthModel;
import net.caixiaomi.info.model.CustomerModel;
import net.caixiaomi.info.ui.dialog.AccountsFilterDialogFragment;
import net.caixiaomi.info.util.EventWhat;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import icepick.State;

/**
 * 账户明细
 */

public class AccountDetailsActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.total_price)
    TextView mTotalPrice;
    @BindView(R.id.tab)
    TabLayout mTabLayout;

    @BindView(R.id.pager)
    ViewPager mViewPager;
    @BindView(R.id.view1)
    View mBottomView;
    @State
    int mPosition;
    @State
    private int mCurrentTimeType = 2;

    private List<CustomerModel> mFilter = new ArrayList<>();
    private String mCurrentFilter = "";
    private TextView mFilterMenu;
    private CommonFragmentPageAdapter mAdapter;
    private TabLayout.TabLayoutOnPageChangeListener mChangeListener = new TabLayout.TabLayoutOnPageChangeListener(mTabLayout) {

        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            AppHelper.sendStatistics(position == 0 ? "zhmxquanbu" : position == 1 ? "zhmxjiangjin" : position == 2 ? "zhmxchongzhi" : position == 3 ? "zhmxgoucai" : position == 4 ? "zhmxtixian" : "zhmxhongbao");
            mPosition = position;
        }
    };

    @Override
    protected int layout() {
        return R.layout.act_account_details;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] accountFilter = getResources().getStringArray(R.array.C_ACCOUNT_FILTER);
        for (int index = 0; index < accountFilter.length; index++) {
            CustomerModel model = new CustomerModel();
            model.setName(accountFilter[index]);
            model.setId(index + 1);
            if (index == 1) {
                model.setSelected(true);
                mCurrentFilter = model.getName();
                mCurrentTimeType = model.getId();
            }
            mFilter.add(model);
        }
        CustomerModel model = new CustomerModel();
        model.setName(getString(R.string.C_ALL));
        model.setId(0);
        mFilter.add(model);

        String[] tabArray = getResources().getStringArray(R.array.TAB_DETAIL_ARRAY);
        List<Fragment> data = new ArrayList<>();
        List<CommonTab> titles = new ArrayList<>();
        for (int index = 0; index < tabArray.length; index++) {
            AccountDetailsFragment fragment = new AccountDetailsFragment();
//            Bundle bundle = new Bundle();
//            bundle.putInt("timeType", mCurrentTimeType);
//            fragment.setArguments(bundle);
            CommonTab tab = new CommonTab(index, tabArray[index]);
            titles.add(tab);
            fragment.setType(index);
            data.add(fragment);
        }

        mAdapter = new CommonFragmentPageAdapter(getSupportFragmentManager(), titles, data);
        mAdapter.setFilter(String.valueOf(mCurrentTimeType));
        mViewPager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        LinearLayout linearLayout = (LinearLayout) mTabLayout.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.layout_divider_vertical));
        mViewPager.addOnPageChangeListener(mChangeListener);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setCurrentItem(mPosition);
//        loadData();
    }

//    private void loadData() {
//        JSONObject params = new JSONObject();
//        params.put("time", String.valueOf(System.currentTimeMillis()));
//        params.put("timeType", mCurrentTimeType);
//        RequestService requestService = RetrofitManage.getInstance().getRequestService();
//        Call<BaseCallModel<CountMoneyCurrentMonthModel>> baseCallModelCall = requestService.countMoneyCurrentMonth(params);
//        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<CountMoneyCurrentMonthModel>>(this) {
//            @Override
//            public void onSuccess(BaseCallModel<CountMoneyCurrentMonthModel> data) {
//                mBottomView.setVisibility(View.VISIBLE);
//                CountMoneyCurrentMonthModel model = data.data;
//                if (model != null) {
//                    bindData(model);
//
//                }
//            }
//
//            @Override
//            public void onFail(ResponseError error) {
//                mBottomView.setVisibility(View.GONE);
//                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
//                    ToastUtil.s(error.getMessage());
//                }
//            }
//
//            @Override
//            public void onError() {
//                mBottomView.setVisibility(View.GONE);
//            }
//        });
//
//
//    }

    private void bindData(CountMoneyCurrentMonthModel model) {
        try {
            mBottomView.setVisibility(View.VISIBLE);
            List<String> moneys = new ArrayList<>();
            String moneyChat = getString(R.string.C_MONEY);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(model.getRechargeMoney()).append(moneyChat);
            String rechargeMoney = stringBuilder.toString();
            moneys.add(rechargeMoney);
            stringBuilder.setLength(0);

            stringBuilder.append(model.getWithDrawMoney()).append(moneyChat);
            String withdrawMoney = stringBuilder.toString();
            moneys.add(withdrawMoney);
            stringBuilder.setLength(0);

            stringBuilder.append(model.getBuyMoney()).append(moneyChat);
            String buyMoney = stringBuilder.toString();
            moneys.add(buyMoney);
            stringBuilder.setLength(0);

            stringBuilder.append(model.getRewardMoney()).append(moneyChat);
            String rewardMoney = stringBuilder.toString();
            moneys.add(rewardMoney);
            stringBuilder.setLength(0);

            stringBuilder.append(getString(R.string.C_TOTAL_PRICE)).append(":").append("\n");
            String text = stringBuilder.toString();
            stringBuilder.append(getString(R.string.C_RECHARGE)).append(rechargeMoney).append(" , ");
            stringBuilder.append(getString(R.string.C_WITHDRAW)).append(withdrawMoney).append(" , ");
            stringBuilder.append(getString(R.string.C_BUY)).append(buyMoney).append(" , ");
            stringBuilder.append(getString(R.string.C_LOTTERY)).append(rewardMoney);

            SpannableString spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), 0, text.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            int fromIndex = 0;
            for (String money : moneys) {
                if (fromIndex > stringBuilder.length())
                    return;
                fromIndex = stringBuilder.indexOf(money, fromIndex);
                spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), fromIndex, fromIndex + money.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                fromIndex = fromIndex + money.length();
            }
            mTotalPrice.setText(spannableString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.edit, menu);
        MenuItem item = menu.findItem(R.id.btn_edit);
        if (mFilterMenu == null) {
            mFilterMenu = new TextView(this);
            mFilterMenu.setGravity(Gravity.CENTER_VERTICAL);
            mFilterMenu.setPadding(0, (int) getResources().getDimension(R.dimen.padding_8), (int) getResources().getDimension(R.dimen.padding_12), (int) getResources().getDimension(R.dimen.padding_8));
            mFilterMenu.setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.padding_5));
            mFilterMenu.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text));
            mFilterMenu.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(CommonApp.getInstance(), R.mipmap.ic_expand_more), null);
            mFilterMenu.setText(mCurrentFilter);
            mFilterMenu.setOnClickListener(this);
            mFilterMenu.setTextColor(getResources().getColor(R.color.bar_background_text_color));
        }
        item.setActionView(mFilterMenu);

//        mMenuFilter.setTitle(mCurrentFilter);
        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return true;
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_ACCOUNT_REFRESH:
                    handlePost(event.getMessage());
                    break;
                case EventWhat.EVENT_ACCOUNT_UPDATE_PRICE:
                    CountMoneyCurrentMonthModel countMoneyCurrentMonthModel = JSON.parseObject(event.getMessage(), CountMoneyCurrentMonthModel.class);
//                    bindData(countMoneyCurrentMonthModel);
                    break;

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlePost(String message) {
        try {
            try {
                mFilter = JSON.parseObject(message, new TypeToken<List<CustomerModel>>() {
                }.getType());
                for (CustomerModel item : mFilter) {
                    if (item.isSelected()) {
                        mCurrentTimeType = item.getId();
                        mCurrentFilter = item.getName();
                        break;
                    }
                }
                mAdapter.setFilter(String.valueOf(mCurrentTimeType));
                mFilterMenu.setText(mCurrentFilter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "zhanghumingxi-view");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "zhanghumingxi-view");
    }

    @Override
    public void onBackPressed() {
        AppHelper.sendStatistics("zhmxfanhui");
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        String text = JSON.toJSONString(mFilter);
        AccountsFilterDialogFragment dialog = new AccountsFilterDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("data", text);
        dialog.setArguments(bundle);
        dialog.show(getSupportFragmentManager(), dialog.getClass().getName());
    }
}
